import axios from 'axios'

const API_BASE_URL = 'http://localhost:5000/api'

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证token
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('auth_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API Error:', error)
    // 如果是401错误（未认证），清除token并跳转到登录页
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('auth_token')
      localStorage.removeItem('user_info')
      // 如果当前不在登录页，则跳转到登录页
      if (window.location.hash !== '#/login') {
        window.location.href = '#/login'
      }
    }
    return Promise.reject(error)
  }
)

export const chainAPI = {
  // 关系图管理
  getCharts() {
    return api.get('/charts')
  },

  getChart(chartId) {
    return api.get(`/charts/${chartId}`)
  },

  createChart(chartData) {
    return api.post('/charts', chartData)
  },

  updateChart(chartId, chartData) {
    return api.put(`/charts/${chartId}`, chartData)
  },

  deleteChart(chartId) {
    return api.delete(`/charts/${chartId}`)
  },

  duplicateChart(chartId) {
    return api.post(`/charts/${chartId}/duplicate`)
  },

  getDefaultChart() {
    return api.get('/charts/default')
  },

  // 原有接口，支持chart_id参数
  getChainData(chartId) {
    const params = chartId ? { chart_id: chartId } : {}
    return api.get('/chain-data', { params })
  },

  getNodes(chartId) {
    const params = chartId ? { chart_id: chartId } : {}
    return api.get('/nodes', { params })
  },

  createNode(nodeData) {
    return api.post('/nodes', nodeData)
  },

  updateNode(nodeId, nodeData) {
    return api.put(`/nodes/${nodeId}`, nodeData)
  },

  deleteNode(nodeId) {
    return api.delete(`/nodes/${nodeId}`)
  },

  getRelationships(chartId) {
    const params = chartId ? { chart_id: chartId } : {}
    return api.get('/relationships', { params })
  },

  createRelationship(relationshipData) {
    return api.post('/relationships', relationshipData)
  },

  updateRelationship(relationshipId, relationshipData) {
    return api.put(`/relationships/${relationshipId}`, relationshipData)
  },

  deleteRelationship(relationshipId) {
    return api.delete(`/relationships/${relationshipId}`)
  }
}

export const authAPI = {
  // 用户注册
  register(userData) {
    return api.post('/auth/register', userData)
  },

  // 用户登录
  login(credentials) {
    return api.post('/auth/login', credentials)
  },

  // 获取用户资料
  getProfile() {
    return api.get('/auth/profile')
  },

  // 更新用户资料
  updateProfile(userData) {
    return api.put('/auth/profile', userData)
  },

  // 修改密码
  changePassword(passwordData) {
    return api.post('/auth/change-password', passwordData)
  },

  // 验证token
  verifyToken(token) {
    return api.post('/auth/verify-token', { token })
  },

  // 登出（清除本地存储）
  logout() {
    localStorage.removeItem('auth_token')
    localStorage.removeItem('user_info')
    window.location.href = '#/login'
  }
}

export default api